package com.yawn.zk.controller;

import com.yawn.zk.client.ZkClient;
import com.yawn.zk.controller.lock.ZkLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ZkLock2Controller {

    @Autowired
    private ZkClient zkClient;


    @GetMapping("t2")
    public String lock() {
        SaleGoods saleGoods = new SaleGoods();
        for (int i = 0; i < 3; i++) {
            new Thread(saleGoods).start();
        }
        return "okay!";
    }



    class SaleGoods implements Runnable {
        private int restNum = 100;
        @Override
        public void run() {
            // 若还有余量，就一直购买
            while (restNum > 0) {
                try {
                    buyWithLock();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        /**
         * 此锁不能保证公平性，公平锁的实现可参考：
         * @see ZkLockController
         */
        private void buyWithLock() {
            //创建分布式锁, 锁的节点路径为/lock2
            ZkLock zkLock = new ZkLock(zkClient, "/lock2");
            zkLock.acquire();
            //获得了锁, 进行业务流程
            buy();
            //完成业务流程, 释放锁
            zkLock.release();
        }

        void buy() {
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (restNum > 0) {
                System.out.println(Thread.currentThread().getName()
                        + "买到一件，还剩：" + --restNum);
            } else {
                System.out.println(Thread.currentThread().getName()
                        + "没有买到，还剩：" + restNum + "，我们深感抱歉！");
            }

        }
    }


}
